package com.heze.xunhuan.utils;

import com.heze.xunhuan.config.AppConfig;
import io.minio.*;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * MinIO工具类
 *
 * @author heze-xunhuan
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MinioUtil {

    private final AppConfig appConfig;

    /**
     * 上传文件到MinIO
     *
     * @param file 文件
     * @param folder 文件夹名称
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file, String folder) {
        try {
            // 创建MinIO客户端
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(appConfig.getMinio().getEndpoint())
                    .credentials(appConfig.getMinio().getAccessKey(), appConfig.getMinio().getSecretKey())
                    .build();

            // 检查bucket是否存在，不存在则创建
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(appConfig.getMinio().getBucketName())
                    .build());
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(appConfig.getMinio().getBucketName())
                        .build());
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = folder + "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + 
                    "/" + UUID.randomUUID().toString().replace("-", "") + fileExtension;

            // 上传文件
            try (InputStream inputStream = file.getInputStream()) {
                minioClient.putObject(PutObjectArgs.builder()
                        .bucket(appConfig.getMinio().getBucketName())
                        .object(fileName)
                        .stream(inputStream, file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
            }

            // 返回文件访问URL
            return appConfig.getFile().getAccessUrl() + "/" + fileName;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 删除MinIO中的文件
     *
     * @param fileName 文件名
     */
    public void deleteFile(String fileName) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(appConfig.getMinio().getEndpoint())
                    .credentials(appConfig.getMinio().getAccessKey(), appConfig.getMinio().getSecretKey())
                    .build();

            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(appConfig.getMinio().getBucketName())
                    .object(fileName)
                    .build());
        } catch (Exception e) {
            log.error("文件删除失败", e);
            throw new RuntimeException("文件删除失败", e);
        }
    }
}